package com.lovo.test.ATM;

import com.lovo.test.ATM.ATM;
import com.lovo.test.Util.Util;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.ArrayList;

//登陆界面
public class LoginPanel extends JPanel implements ActionListener {

    private JTextField userField;//账号输入文本框
    private JPasswordField pwdField;//密码输入框

     private int number = 3;
     private int index = 0;

    //以下是图片封装
    private Icon loginImg = Util.getIcon("/ATMimages/buttonLand.jpg");//登录按键
    private Icon registerImg = Util.getIcon("/ATMimages/buttonLogin.jpg");//注册按键


    private ATM frame;//包含ATM。JFrame 对象



    private JButton loginBut;//登陆按钮对象

    public LoginPanel(ATM frame){
        this.frame=frame;


        //背景图片


        this.setLayout(null);

        //设置透明
        this.setOpaque(false);

        //以下是按钮
        //登陆按钮
        loginBut = new JButton(loginImg);
        loginBut.setBounds(200,330,140,50);
        this.add(loginBut);
        loginBut.addActionListener(this);



        //以下是文本框
        userField = new JTextField();//账号文本框
        userField.setBounds(350,170,100,20);
        this.add(userField);

        pwdField = new JPasswordField();//密码文本框
        pwdField.setBounds(350,200,100,20);
        this.add(pwdField);

        //以下是标签
        JLabel userLabel = new JLabel("账号");
        userLabel.setBounds(300,170,50,20);
        add(userLabel);

        JLabel pwdLabel = new JLabel("密码");
        pwdLabel.setBounds(300,200,50,20);
        add(pwdLabel);

    }

    //登录
    public boolean login(){
         ArrayList<User> loginUser=frame.getUsers();
        for (int i = 0; i<frame.getUsers().size();i++){
            if (userField.getText().equals(frame.getUsers().get(i).getUserName())
                    &&String.valueOf(pwdField.getPassword()).equals(frame.getUsers().get(i).getPassWord())){
                  frame.setUserName(loginUser.get(i));//将登录成功的对象传给frame下面的用户属性
                   index=i;
                return true;
            }
        }
        return false;
    }



    //跳转页面
    @Override
    public void actionPerformed(ActionEvent e) {

        if (e.getSource()==loginBut){
            boolean flag=login();
            if (flag){
                JOptionPane.showMessageDialog(this,"登陆成功");
                frame.switchPanel("菜单");//跳转到菜单界面
                number=3;
            }else {
                number--;
                JOptionPane.showMessageDialog(this,"账号或密码错误,你还有"+number+"次机会");

                if (number==0){
                    System.exit(0);
                }
            }
        }
    }

    public int getIndex() {
        return index;
    }

    public void setIndex(int index) {
        this.index = index;
    }
}
